<template>
	<view class="content">
		<view class="">
			<u-upload  ref="uUpload"   v-show="show"  :show-progress="false" :source-type="['camera']" :size-type="['compressed']" :auto-upload="false"  @on-error="handleError"  @afterRead="afterRead" @delete="deletePic" @on-choose-complete="uppic"
				  multiple :maxCount="1" @on-remove="onRemove"
				></u-upload>
				<view class="loading" v-show="!show">
					<u-loading  mode="circle"></u-loading>	
					<text>上传中...</text>
				</view>
				
		</view>
		<canvas type="2d" id="myCanvas" style="position: absolute;top: -9999999px; left: -9999999px;"></canvas>
	</view>
</template>
<script>
	import {
		UPLOAD_URL
	} from '@/env.js';
	export default {
		data() {
			return {

				maxSize: 500, // 图片宽高的最大尺寸
				myCanvas: null,
				myCtx: null,
				dpr: null,
				canvasDisplayW: 300,
				canvasDisplayH: 300,
				fillNum: null,
				show:true,
				setTime:'',
			}
		},
		mounted() {
			this.initCanvas();
		},
		onLoad(){
		
		},
		props:['adress','phone','type','logid'], // 根据需求接收需要传递的值
		watch:{
			show(newVal) {
				if(newVal == true){
					if(this.setTime != ''){
					clearTimeout(this.setTime);	
					}
				}else{
				   this.setTime = setTimeout(()=>{
				  	  if (newVal == false && this.$refs.uUpload.lists.length < 1) {
				  	  	this.show = true;
				  	  	this.$utils.toast('请重新上传图片');
				  	  }									
				   },5000)	
				}
			   
				  
			},	
		},
		methods: {
			// 图片移除时触发
			onRemove(index, lists, name){
				this.type == 1 ? this.$emit('onRemove','1') : this.$emit('onRemove','2');
					
			},
			//  上传失败时触发
			handleError(data, index, lists) {
				this.$utils.toast('上传失败！');
				this.show = true;
				this.$refs.uUpload.lists = [];
				//this.$refs.uUpload.remove(index);
			},
			uppic(e){
				this.show = false;
				let imgz = e;
				this.chooseImage(imgz)
			},	
			// 初始化canvas
			initCanvas() {
				const _ = this;
				// 若在自定义组件中，此处应写为this.createSelectorQuery();
				const query = wx.createSelectorQuery();
				query.select('#myCanvas')
					.fields({
						node: true,
						size: true
					})
					.exec((res) => {
						let myCanvas = res[0].node;
						let myCtx = myCanvas.getContext('2d');
						myCtx.font = "normal bold 12px PingFangSC-Regular";
						const dpr = wx.getSystemInfoSync().pixelRatio;

						this.myCanvas = myCanvas
						this.myCtx = myCtx
						this.dpr = dpr
					})
			},
			// 压缩图片
			compress(imgW, imgH) {
				const _ = this;
				const dpr = _.dpr;
				const maxSize = _.maxSize;
				const ratio = imgW / imgH;
				let canvas = _.myCanvas;
				let ctx = _.myCtx;

				let canvasWidth = imgW;
				let canvasHeight = imgH;
				while (canvasWidth > maxSize || canvasHeight > maxSize) {
					if (canvasWidth > maxSize) {
						canvasWidth = maxSize;
						canvasHeight = maxSize / ratio;
					} else if (canvasHeight > maxSize) {
						canvasHeight = maxSize;
						canvasWidth = maxSize * ratio;
					}
				}
				canvas.width = dpr * canvasWidth;
				canvas.height = dpr * canvasHeight;
				ctx.scale(dpr, dpr);
				return {
					canvasWidth,
					canvasHeight
				}
				
			},
			// 图片添加水印
			addMask(img, imgW, imgH) {
				const _ = this;
				// const date = 'namename';
				const fillTexts = [];
				fillTexts.push('社区：' + _.adress);
				fillTexts.push('时间：' + _.getNowTime());
				fillTexts.push('手机号：' + _.phone);
				fillTexts.push('订单号：' + _.logid);
				
			
				if (!_.myCanvas) {
					_.initCanvas();
				}
				let canvas = _.myCanvas;
				let ctx = _.myCtx;
				// 1. 压缩图片
				let {
					canvasWidth,
					canvasHeight
				} = _.compress(imgW, imgH);
				return new Promise((resolve, reject) => {
					// 2. 生成图片
					let image = canvas.createImage();
					image.src = img;
					image.onload = (e) => {
						ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight);
						
						ctx.fillStyle = '#222';
						ctx.shadowColor = "#333"; // 阴影颜色
						ctx.shadowOffsetX = 0; // 阴影x轴位移。正值向右，负值向左。
						ctx.shadowOffsetY = 0; // 阴影y轴位移。正值向下，负值向上。
						ctx.shadowBlur = 0; // 阴影模糊滤镜。数据越大，扩散程度越大。
						
						// fillTexts
						this.fillNum = canvasHeight;
						fillTexts.forEach((mark, index) => {
							this.fillNum -= 10
							ctx.fillText(mark, 10, this.fillNum -= 10);
						});
						// 4. 将canvas转为图片
						wx.canvasToTempFilePath({
							destWidth: canvasWidth,
							destHeight: canvasHeight,
							canvas: canvas,
							success(res) {
								resolve(res.tempFilePath);
							},
							fail(error) {
								reject(error)
							}
						})
					}
					image.onerror = (e) => {
						this.$utils.toast('上传失败！');
						this.show = true;
						this.$refs.uUpload.lists = [];
					}
				})
			},
			// 选择图片
			chooseImage(imgPath) {
				const _ = this;
				let imgPathitem = imgPath[0]
				wx.getImageInfo({
					src: imgPath[0].url,
					success(res) {
						// 2. 添加水印
						/* _.$refs.uUpload.lists = []; */
						_.addMask(imgPathitem.url, res.width, res.height).then(imgPath => {
							_.$refs.uUpload.lists=[{
								size: imgPathitem.size,
								thumb: imgPath,
								type: imgPathitem.type,
								url: imgPath,
							}]
	
							uni.uploadFile({
									url: UPLOAD_URL, //仅为示例，非真实的接口地址
									filePath:imgPath,
									name: 'file',
									formData: {
										'modular_name':'repair'
									},
									success: (uploadFileRes) => {
										let data = JSON.parse(uploadFileRes.data);
										if(data.code  == 200){
											// type 1是上面的上传 2是下面的上传
											if(_.type == 1){
												_.$emit('imgSuccess',data.data.file_url,1)
											}else{
												_.$emit('imgSuccess',data.data.file_url,2)
											}
											
										}else{
										_.$utils.toast(data.data.message);
										}
										_.show = true;
										
									},fail(res) {
										_.$utils.toast('上传失败!');
										_.$refs.uUpload.lists = [];
										_.show = true;		
					}
								});
						});
					   
						
					},
					fail(res) {
						_.$utils.toast('上传失败!');
						_.$refs.uUpload.lists = [];
						_.show = true;	
					}
				})
				// 

			},
			getNowTime() {
				var date = new Date(),
					year = date.getFullYear(),
					month = date.getMonth() + 1,
					day = date.getDate(),
					hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
					minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
					second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				month >= 1 && month <= 9 ? (month = "0" + month) : "";
				day >= 0 && day <= 9 ? (day = "0" + day) : "";
				return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
			}
		},
	}
</script>

<style lang="scss" scoped>
	.iconfont {
		color: #0da297;
		font-size: 50rpx;
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
	}

	.form {
		padding: 0 30rpx;
		padding-top: 20rpx;
		padding-left: 30rpx;
	}

	.phone {
		position: relative;
		padding-left: 70rpx;
	}

	.verification-code {
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
	}

	.submit {
		padding-top: 60rpx;
	}

	.get-code {
		color: #0da297;
		font-size: 28rpx;
	}

	//上传
	.common-tips {
		font-size: 30rpx;
		font-weight: bold;
		color: #2fb1a7;
		padding: 20rpx 0;
	}

	.upload-txt {
		line-height: 50rpx;
		padding-top: 12rpx;
	}

	.upload-txt text:first-child {
		font-size: 26rpx;

		color: #e62d2d;
	}

	.upload-txt text:last-child {
		font-size: 26rpx;

		color: #727272;
	}

	.upload-demo {
		font-size: 28rpx;
		color: #727272;
		padding: 10rpx 0;
	}
	.loading {
		
	}
</style>
<style>
	.u-radio {
		margin-bottom: 30rpx !important;
	}

	page {
		background-color: #fff;
	}
</style>